import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:base_flutter/src/network/manager.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/logger.dart';
import '../models/post_model.dart';
import '../models/user_profile_model.dart';

class ApiService {
  static final ApiService _instance = ApiService._internal();
  factory ApiService() => _instance;

  final NetworkManager _networkManager = NetworkManager();
  final Connectivity _connectivity = Connectivity();
  static const Duration _hotPostsCacheTtl = Duration(hours: 2);
  static const String _hotPostsCachePrefix = 'cache_hot_posts_';

  ApiService._internal() {
    // 通过 dart-define 注入，默认使用开发机地址
    final String baseUrl = const String.fromEnvironment(
      'API_BASE_URL',
      defaultValue: 'http://192.168.1.201:8080',
    );
    _networkManager.setBaseUrl(baseUrl);
    Logger.d('API_SERVICE', 'Base URL set to: $baseUrl');
  }

  // 初始化ApiService（包括恢复token）
  Future<void> initialize() async {
    await _restoreAuthToken();
  }

  // 从本地存储恢复认证token
  Future<void> _restoreAuthToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('auth_token');
      if (token != null && token.isNotEmpty) {
        _networkManager.setHeaders('Authorization', 'Bearer $token');
        Logger.d('API_SERVICE',
            'Restored auth token from local storage: Bearer $token');
      } else {
        Logger.d('API_SERVICE', 'No auth token found in local storage');
      }
    } catch (e) {
      Logger.e('API_SERVICE', 'Failed to restore auth token',
          exception: e as Exception);
    }
  }

  // 设置用户ID
  Future<void> setUserId(String userId) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('user_id', userId);
    Logger.d('API_SERVICE', 'User ID saved to local storage: $userId');
  }

  // 获取用户ID
  Future<String?> getUserId() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userId = prefs.getString('user_id');
      Logger.d('API_SERVICE', 'Retrieved user ID from local storage: $userId');
      return userId;
    } catch (e) {
      Logger.e('API_SERVICE', 'Failed to get user ID',
          exception: e as Exception);
      return null;
    }
  }

  // 检查网络连接状态
  Future<bool> checkNetworkConnection() async {
    try {
      final connectivityResult = await _connectivity.checkConnectivity();
      return connectivityResult != ConnectivityResult.none;
    } catch (e) {
      return false;
    }
  }

  // 取消请求的方法
  void cancelRequest(String requestId, [String? reason]) {
    _networkManager.cancelRequest(requestId, reason);
  }

  // 取消所有请求
  void cancelAllRequests([String? reason]) {
    _networkManager.cancelAllRequests(reason);
  }

  // 发送验证码（purpose: login/register）
  Future<void> sendVerificationCode(String phone, String purpose,
      {String requestId = 'send_verification_code'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      return await _networkManager.post(
        '/sms/sendCode',
        data: {"phone": phone, "purpose": purpose},
        contentType: Headers.formUrlEncodedContentType,
        requestId: requestId,
        retryCount: 2,
        retryDelayMs: 1500,
      );
    } catch (e) {
      throw _formatException(e, '发送验证码失败');
    }
  }

  // 验证验证码
  Future<bool> verifyCode(String phone, String code, String purpose,
      {String requestId = 'verify_code'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      final result = await _networkManager.post(
        '/sms/verifyCode',
        data: {"phone": phone, "code": code, "purpose": purpose},
        contentType: Headers.formUrlEncodedContentType,
        requestId: requestId,
        retryCount: 2,
        retryDelayMs: 1500,
      );
      return result['success'] == true;
    } catch (e) {
      throw _formatException(e, '验证码验证失败');
    }
  }

  // 用户注册（第一步：手机号验证和密码设置）返回临时注册ID
  Future<String> registerStepOne(
      String phone, String password, String confirmPassword, String code,
      {String requestId = 'register_step_one'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    // 记录用户提交的数据，便于调试
    Logger.d('REGISTER_API', '=== Register Step One Request ===');
    Logger.d('REGISTER_API', 'Phone: $phone');
    // 密码记录时进行脱敏处理
    Logger.d('REGISTER_API', 'Password: ******** (length: ${password.length})');
    Logger.d('REGISTER_API',
        'Confirm Password: ******** (length: ${confirmPassword.length})');
    Logger.d('REGISTER_API', 'Verification Code: $code');

    try {
      final result = await _networkManager.post(
        '/user/register/step-one',
        data: {
          "phone": phone,
          "password": password,
          "confirmPassword": confirmPassword,
          "code": code
        },
        requestId: requestId,
        retryCount: 2,
        retryDelayMs: 1500,
      );
      Logger.d('REGISTER_API', 'Step One Response: $result');
      String? tempId;
      if (result is Map) {
        final data = (result['data'] is Map) ? result['data'] as Map : result;
        // 常规：camelCase
        if (data['tempRegistrationId'] != null) {
          tempId = data['tempRegistrationId'].toString();
        }
        // 兼容：snake_case
        if ((tempId == null || tempId.isEmpty) &&
            data['temp_registration_id'] != null) {
          tempId = data['temp_registration_id'].toString();
        }
        // 兜底：可能后端返回 id 字段
        if ((tempId == null || tempId.isEmpty) && data['id'] != null) {
          tempId = data['id'].toString();
        }
      } else if (result != null) {
        // 兜底：如果是简单类型，尝试直接转字符串数字
        final s = result.toString();
        if (RegExp(r'^\d+$').hasMatch(s)) {
          tempId = s;
        }
      }
      if (tempId == null || tempId.isEmpty) {
        throw NetworkException(message: '未获取到临时注册ID');
      }
      // 持久化临时注册ID，便于后续页面读取
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('pending_temp_registration_id', tempId);
      return tempId;
    } catch (e) {
      throw _formatException(e, '注册失败');
    }
  }

  // 用户注册（第二步：完善信息，需传入后端返回的临时注册ID）
  Future<Map<String, dynamic>> registerStepTwo({
    required String tempRegistrationId,
    required String code,
    required String username,
    required String nickname,
    String? email,
    String? bio,
    required String gender,
    required List<String> skills,
    String requestId = 'register_step_two',
  }) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      // 记录请求参数（敏感信息不打印明文）
      Logger.d('REGISTER_API', '=== Register Step Two Request ===');
      Logger.d('REGISTER_API', 'tempRegistrationId: ' + tempRegistrationId);
      Logger.d(
          'REGISTER_API', 'username: ' + username + ', nickname: ' + nickname);
      Logger.d('REGISTER_API', 'email: ' + (email ?? ''));
      Logger.d('REGISTER_API',
          'gender: ' + gender + ', skillsCount: ' + skills.length.toString());

      final result = await _networkManager.post(
        '/user/register/step-two',
        data: {
          "tempRegistrationId":
              int.tryParse(tempRegistrationId) ?? tempRegistrationId,
          "code": code,
          "username": username,
          "nickname": nickname,
          "email": email,
          "bio": bio,
          "gender": gender,
          "skills": skills,
        },
        requestId: requestId,
        retryCount: 2,
        retryDelayMs: 1500,
      );
      Logger.d('REGISTER_API', 'Step Two Response: ' + result.toString());
      return result;
    } catch (e) {
      throw _formatException(e, '注册失败');
    }
  }

  // 兼容旧调用：注册（完整）- 临时占位以保证编译通过
  // 请尽快改为：先调用 registerStepOne 获取 tempRegistrationId，再调用 registerStepTwo
  Future<Map<String, dynamic>> registerUser({
    required String phone,
    required String code,
    required String username,
    String? email,
    String? bio,
    required List<String> skills,
    String requestId = 'register_user_compat',
  }) async {
    throw NetworkException(
      message: '注册流程已调整：请在步骤一设置密码并获取临时ID，再调用步骤二完成信息',
    );
  }

  // 手机号验证码登录（使用统一登录接口 /user/login）
  Future<Map<String, dynamic>> loginWithPhone(
      {required String phone,
      required String code,
      String requestId = 'login_with_phone'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      final result = await _networkManager.post(
        '/user/login',
        data: {"loginType": "phone", "phone": phone, "code": code},
        requestId: requestId,
        retryCount: 2,
        retryDelayMs: 1500,
      );

      // 登录成功后设置token
      if (result['code'] == 200 || result['code'] == 0) {
        final data = result['data'];
        if (data != null && data['accessToken'] != null) {
          await setAuthToken(data['accessToken']);
          Logger.d('LOGIN', '登录成功，token已设置');
        }
      }

      return result;
    } catch (e) {
      throw _formatException(e, '登录失败');
    }
  }

  // 账号密码登录（使用统一登录接口 /user/login）
  Future<Map<String, dynamic>> loginWithPassword(
      {required String username,
      required String password,
      String requestId = 'login_with_password'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      final result = await _networkManager.post(
        '/user/login',
        data: {
          "loginType": "password",
          "username": username,
          "password": password
        },
        requestId: requestId,
        retryCount: 3, // 登录请求重试次数增加到3次
        retryDelayMs: 2000, // 登录请求重试延迟增加到2秒
      );

      // 登录成功后设置token
      if (result['code'] == 200 || result['code'] == 0) {
        final data = result['data'];
        if (data != null && data['accessToken'] != null) {
          await setAuthToken(data['accessToken']);
          Logger.d('LOGIN', '登录成功，token已设置');
        }
      }

      return result;
    } catch (e) {
      throw _formatException(e, '登录失败');
    }
  }

  // 上传头像
  Future<Map<String, dynamic>> uploadAvatar(File image,
      {String requestId = 'upload_avatar'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    final formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(image.path, filename: 'avatar.jpg'),
    });

    try {
      return await _networkManager.post(
        '/api/user/upload/avatar',
        data: formData, // 使用data参数传递FormData
        contentType: 'multipart/form-data',
        requestId: requestId,
        retryCount: 1, // 文件上传重试次数减少
        retryDelayMs: 3000, // 但延迟增加
      );
    } catch (e) {
      throw _formatException(e, '上传头像失败');
    }
  }

  /// 上传视频文件
  /// @param videoFile 视频文件
  Future<Map<String, dynamic>> uploadVideo(File videoFile,
      {String requestId = 'upload_video'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_UPLOAD_VIDEO', '开始上传视频文件: ${videoFile.path}');

      // 获取文件大小用于日志
      final fileSize = await videoFile.length();
      Logger.d('API_UPLOAD_VIDEO',
          '视频文件大小: ${(fileSize / 1024 / 1024).toStringAsFixed(2)}MB');

      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(videoFile.path,
            filename: videoFile.path.split('/').last),
      });

      // 使用Dio直接请求，设置更长的超时时间（视频上传需要更长时间）
      final dio = Dio();
      dio.options.baseUrl = 'http://192.168.1.201:8080'; // 使用固定的baseUrl
      dio.options.connectTimeout = const Duration(minutes: 1);
      dio.options.sendTimeout = const Duration(minutes: 5); // 发送超时：5分钟
      dio.options.receiveTimeout = const Duration(minutes: 5); // 接收超时：5分钟

      // 从SharedPreferences获取token（与NetworkManager保持一致）
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('auth_token');
      if (token != null && token.isNotEmpty) {
        dio.options.headers['Authorization'] = 'Bearer $token';
      }

      final response = await dio.post(
        '/api/user/upload/video',
        data: formData,
        options: Options(
          contentType: 'multipart/form-data',
        ),
      );

      Logger.d('API_UPLOAD_VIDEO', '视频上传成功: ${response.data}');
      return response.data;
    } catch (e) {
      Logger.e('API_UPLOAD_VIDEO', '视频上传失败: $e');
      throw _formatException(e, '视频上传失败');
    }
  }

  /// 批量上传视频文件
  /// @param videoFiles 视频文件列表
  Future<Map<String, dynamic>> batchUploadVideos(List<File> videoFiles,
      {String requestId = 'batch_upload_videos'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d(
          'API_BATCH_UPLOAD_VIDEOS', '开始批量上传视频文件，数量: ${videoFiles.length}');

      final formData = FormData();
      for (int i = 0; i < videoFiles.length; i++) {
        formData.files.add(MapEntry(
            'files',
            await MultipartFile.fromFile(videoFiles[i].path,
                filename: videoFiles[i].path.split('/').last)));
      }

      final result = await _networkManager.post(
        '/api/user/upload/batch/videos',
        data: formData,
        contentType: 'multipart/form-data',
        requestId: requestId,
        retryCount: 1,
        retryDelayMs: 10000, // 批量上传延迟更长
      );

      Logger.d('API_BATCH_UPLOAD_VIDEOS', '批量视频上传成功: $result');
      return result;
    } catch (e) {
      Logger.e('API_BATCH_UPLOAD_VIDEOS', '批量视频上传失败: $e');
      throw _formatException(e, '批量视频上传失败');
    }
  }

  /// 上传单张图片
  /// @param imageFile 图片文件
  Future<Map<String, dynamic>> uploadPostImage(File imageFile,
      {String requestId = 'upload_post_image'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_UPLOAD_POST_IMAGE', '开始上传图片文件: ${imageFile.path}');

      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(imageFile.path,
            filename: imageFile.path.split('/').last),
      });

      final result = await _networkManager.post(
        '/api/user/upload/post-image',
        data: formData,
        contentType: 'multipart/form-data',
        requestId: requestId,
        retryCount: 1,
        retryDelayMs: 3000,
      );

      Logger.d('API_UPLOAD_POST_IMAGE', '图片上传成功: $result');
      return result;
    } catch (e) {
      Logger.e('API_UPLOAD_POST_IMAGE', '图片上传失败: $e');
      throw _formatException(e, '图片上传失败');
    }
  }

  /// 批量上传图片
  /// @param imageFiles 图片文件列表
  Future<Map<String, dynamic>> batchUploadPostImages(List<File> imageFiles,
      {String requestId = 'batch_upload_post_images'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkConnectionException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_BATCH_UPLOAD_POST_IMAGES',
          '开始批量上传图片文件，数量: ${imageFiles.length}');

      final formData = FormData();
      for (int i = 0; i < imageFiles.length; i++) {
        formData.files.add(MapEntry(
            'files',
            await MultipartFile.fromFile(imageFiles[i].path,
                filename: imageFiles[i].path.split('/').last)));
      }

      final result = await _networkManager.post(
        '/api/user/upload/batch/post-images',
        data: formData,
        contentType: 'multipart/form-data',
        requestId: requestId,
        retryCount: 1,
        retryDelayMs: 5000,
      );

      Logger.d('API_BATCH_UPLOAD_POST_IMAGES', '批量图片上传成功: $result');
      return result;
    } catch (e) {
      Logger.e('API_BATCH_UPLOAD_POST_IMAGES', '批量图片上传失败: $e');
      throw _formatException(e, '批量图片上传失败');
    }
  }

  // 格式化异常信息
  Exception _formatException(dynamic e, String defaultMessage) {
    if (e is NetworkException) {
      // 如果已经是我们自定义的异常类型，直接返回
      return e;
    } else {
      // 否则转换为通用的NetworkException
      String errorMessage = defaultMessage;
      if (e is Exception) {
        errorMessage = e.toString();
        // 去掉异常前缀
        if (errorMessage.startsWith('Exception:')) {
          errorMessage = errorMessage.substring('Exception:'.length).trim();
        }
      }
      return NetworkException(message: errorMessage);
    }
  }

  // 设置认证token
  Future<void> setAuthToken(String token) async {
    final bearerToken = 'Bearer $token';
    _networkManager.setHeaders('Authorization', bearerToken);
    // 通过setExtra方法设置Authorization
    _networkManager.setExtra('Authorization', bearerToken);
    Logger.d('API_SERVICE', 'Auth token set: $bearerToken');

    // 将token保存到本地存储
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('auth_token', token);
    Logger.d('API_SERVICE', 'Auth token saved to local storage');
  }

  // 退出登录 - 清除本地存储的认证信息
  Future<void> logout() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      // 清除token
      await prefs.remove('auth_token');

      // 清除用户ID
      await prefs.remove('user_id');

      // 清除其他可能的用户相关数据
      await prefs.remove('pending_temp_registration_id');

      // 清除NetworkManager中的Authorization header
      _networkManager.setHeaders('Authorization', '');
      _networkManager.setExtra('Authorization', '');

      Logger.d(
          'API_SERVICE', 'User logged out successfully, all auth data cleared');
    } catch (e) {
      Logger.e('API_SERVICE', 'Failed to logout', exception: e as Exception);
      rethrow;
    }
  }

  // 清除所有登录信息缓存（更彻底的清除）
  Future<void> clearAllAuthCache() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      // 清除所有认证相关的key
      await prefs.remove('auth_token');
      await prefs.remove('user_id');
      await prefs.remove('pending_temp_registration_id');

      // 清除NetworkManager中的Authorization header
      _networkManager.setHeaders('Authorization', '');
      _networkManager.setExtra('Authorization', '');

      Logger.d('API_SERVICE', 'All auth cache cleared successfully');
    } catch (e) {
      Logger.e('API_SERVICE', 'Failed to clear auth cache',
          exception: e as Exception);
      rethrow;
    }
  }

  // ==================== 热门动态相关接口 ====================

  /// 获取热门动态列表（旧版简单排序算法）
  /// 支持分页、筛选和排序
  ///
  /// ⚠️ 已废弃：推荐使用新的智能推荐API [getRecommendedPosts]
  ///
  /// 旧算法特点：
  /// - 基于单一维度排序（时间/热度/距离）
  /// - 不考虑用户个性化兴趣
  /// - 无探索新内容机制
  ///
  /// 新算法优势：
  /// - 60% 基于用户兴趣标签推荐
  /// - 20% 系统热门内容保证质量
  /// - 20% 探索性内容发现新兴趣
  ///
  /// 保留原因：向后兼容、A/B测试、降级备用
  ///
  /// @param page 页码，从1开始
  /// @param pageSize 每页数量，默认20
  /// @param category 分类筛选，可选值：全部、技术、设计、咨询、教育、其他
  /// @param sort 排序方式，可选值：latest（最新）、hot（最热）、nearby（附近）
  /// @param postType 动态类型筛选，可选值：text、image、article、video
  /// @deprecated 使用 [getRecommendedPosts] 替代
  @Deprecated('使用 getRecommendedPosts() 获取智能推荐内容')
  Future<List<PostModel>> getHotPosts({
    int page = 1,
    int pageSize = 20,
    String? category,
    String sort = 'latest',
    String? postType,
    String requestId = 'get_hot_posts',
    bool forceRefresh = false,
  }) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_HOT_POSTS',
          '获取热门动态列表 - page: $page, pageSize: $pageSize, category: $category, sort: $sort, postType: $postType');

      final queryParams = <String, dynamic>{
        'page': page,
        'pageSize': pageSize,
        'sort': sort,
      };

      if (category != null && category != '全部') {
        queryParams['category'] = category;
      }
      if (postType != null) {
        queryParams['postType'] = postType;
      }

      final cacheKey = _buildHotPostsCacheKey(
        page: page,
        pageSize: pageSize,
        category: category,
        sort: sort,
        postType: postType,
      );

      if (!forceRefresh) {
        final cachedPosts = await _getHotPostsFromCache(cacheKey);
        if (cachedPosts != null) {
          Logger.d(
            '📦 DATA_CACHE_HIT',
            '==================== 数据缓存命中 ====================',
          );
          Logger.d(
            '📦 DATA_CACHE_HIT',
            '数据来源: 本地缓存 (SharedPreferences)',
          );
          Logger.d(
            '📦 DATA_CACHE_HIT',
            '缓存键: $cacheKey',
          );
          Logger.d(
            '📦 DATA_CACHE_HIT',
            '查询参数: page=$page, category=$category, sort=$sort, postType=$postType',
          );
          Logger.d(
            '📦 DATA_CACHE_HIT',
            '缓存数据量: ${cachedPosts.length} 条动态',
          );
          Logger.d(
            '📦 DATA_CACHE_HIT',
            '=======================================================',
          );
          return cachedPosts;
        }
      }
      
      // 缓存未命中，需要从网络加载
      Logger.d(
        '🌐 DATA_CACHE_MISS',
        '==================== 数据缓存未命中 ====================',
      );
      Logger.d(
        '🌐 DATA_CACHE_MISS',
        '数据来源: 网络请求 (API)',
      );
      Logger.d(
        '🌐 DATA_CACHE_MISS',
        '请求URL: /api/hot-page/posts',
      );
      Logger.d(
        '🌐 DATA_CACHE_MISS',
        '查询参数: page=$page, category=$category, sort=$sort, postType=$postType',
      );
      Logger.d(
        '🌐 DATA_CACHE_MISS',
        forceRefresh ? '原因: 用户强制刷新' : '原因: 缓存不存在或已过期',
      );
      Logger.d(
        '🌐 DATA_CACHE_MISS',
        '=======================================================',
      );

      final result = await _networkManager.get(
        '/api/hot-page/posts',
        params: queryParams, // 移除userId参数，让后端从token获取
        requestId: requestId,
      );

      Logger.d('API_HOT_POSTS', '热门动态列表响应: $result');

      // 🔍 详细日志：检查响应数据结构
      Logger.d('API_HOT_POSTS', '响应code: ${result['code']}');
      Logger.d('API_HOT_POSTS', '响应data类型: ${result['data'].runtimeType}');
      if (result['data'] is Map) {
        Logger.d(
            'API_HOT_POSTS', '响应data.keys: ${(result['data'] as Map).keys}');
        if ((result['data'] as Map).containsKey('list')) {
          Logger.d('API_HOT_POSTS',
              'list长度: ${(result['data']['list'] as List?)?.length ?? 0}');
        }
      }

      if (result['code'] == 200 || result['code'] == 0) {
        final List<dynamic> postsData =
            result['data']['list'] ?? result['data'] ?? [];

        Logger.d('API_HOT_POSTS', '解析后的postsData长度: ${postsData.length}');

        final posts = postsData.map((postJson) {
          // 转换后端字段名到前端字段名
          final Map<String, dynamic> convertedJson =
              Map<String, dynamic>.from(postJson);
          convertedJson['user_id'] = postJson['userId'];
          convertedJson['username'] =
              postJson['userNickname']; // 修复：后端返回userNickname，前端期望username
          convertedJson['user_avatar'] = postJson['userAvatar'];
          convertedJson['post_type'] = postJson['postType'];
          convertedJson['title'] = postJson['title']; // 添加标题字段转换
          convertedJson['cover_url'] = postJson['coverUrl'];
          convertedJson['video_url'] = postJson['videoUrl']; // 添加视频URL字段转换
          convertedJson['likes_count'] = postJson['likesCount'];
          convertedJson['comments_count'] = postJson['commentsCount'];
          convertedJson['shares_count'] = postJson['sharesCount'];
          convertedJson['views_count'] = postJson['viewsCount'];
          convertedJson['is_hot'] = postJson['isHot'];
          convertedJson['skill_tags'] = postJson['tags'] ?? [];
          convertedJson['created_at'] = postJson['createTime'];
          convertedJson['is_liked'] = postJson['isLiked'] ?? false;
          convertedJson['is_followed'] = postJson['isFollowing'] ?? false;

          // 🔍 添加详细的日志输出，包括图片URL信息
          Logger.d('API_HOT_POSTS_DATA', '========== 原始帖子数据 ==========');
          Logger.d('API_HOT_POSTS_DATA', 'ID: ${postJson['id']}');
          Logger.d('API_HOT_POSTS_DATA', '用户: ${postJson['userNickname']}');
          Logger.d('API_HOT_POSTS_DATA', '类型: ${postJson['postType']}');
          Logger.d('API_HOT_POSTS_DATA', '标题: ${postJson['title']}');
          Logger.d('API_HOT_POSTS_DATA', '封面URL (原始): ${postJson['coverUrl']}');
          Logger.d('API_HOT_POSTS_DATA', '视频URL (原始): ${postJson['videoUrl']}');
          Logger.d('API_HOT_POSTS_DATA',
              '视频URL类型: ${postJson['videoUrl'].runtimeType}');
          Logger.d('API_HOT_POSTS_DATA',
              '视频URL是否为空: ${postJson['videoUrl'] == null || postJson['videoUrl'] == ''}');
          Logger.d(
              'API_HOT_POSTS_DATA', 'postJson所有键: ${postJson.keys.toList()}');
          Logger.d('API_HOT_POSTS_DATA',
              '是否包含videoUrl键: ${postJson.containsKey('videoUrl')}');
          Logger.d('API_HOT_POSTS_DATA',
              '是否包含video_url键: ${postJson.containsKey('video_url')}');
          Logger.d('API_HOT_POSTS_DATA', '图片列表 (原始): ${postJson['images']}');
          Logger.d(
              'API_HOT_POSTS_DATA', '用户头像 (原始): ${postJson['userAvatar']}');
          Logger.d('API_HOT_POSTS_DATA', '=============================');

          return PostModel.fromJson(convertedJson);
        }).toList();

        // 保存缓存（仅在成功获取数据后执行）
        Logger.d(
          '✅ DATA_NETWORK_LOADED',
          '==================== 网络数据加载完成 ====================',
        );
        Logger.d(
          '✅ DATA_NETWORK_LOADED',
          '获取数据量: ${posts.length} 条动态',
        );
        Logger.d(
          '✅ DATA_NETWORK_LOADED',
          '正在保存到本地缓存...',
        );
        Logger.d(
          '✅ DATA_NETWORK_LOADED',
          '缓存键: $cacheKey',
        );
        Logger.d(
          '✅ DATA_NETWORK_LOADED',
          '缓存有效期: 2小时',
        );
        Logger.d(
          '✅ DATA_NETWORK_LOADED',
          '=======================================================',
        );
        unawaited(_saveHotPostsToCache(cacheKey, posts));
        return posts;
      } else {
        throw BusinessException(message: result['message'] ?? '获取热门动态失败');
      }
    } catch (e) {
      Logger.e('API_HOT_POSTS', '获取热门动态列表失败: $e');
      rethrow;
    }
  }

  String _buildHotPostsCacheKey({
    required int page,
    required int pageSize,
    String? category,
    required String sort,
    String? postType,
  }) {
    final cat = Uri.encodeComponent(category ?? 'all');
    final type = Uri.encodeComponent(postType ?? 'all');
    return '$_hotPostsCachePrefix$cat-$sort-$type-p$page-s$pageSize';
  }

  Future<List<PostModel>?> _getHotPostsFromCache(String key) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final raw = prefs.getString(key);
      if (raw == null) return null;
      final Map<String, dynamic> jsonMap = jsonDecode(raw);
      final timestamp = DateTime.tryParse(jsonMap['timestamp'] ?? '');
      if (timestamp == null ||
          DateTime.now().difference(timestamp) > _hotPostsCacheTtl) {
        await prefs.remove(key);
        return null;
      }
      final List<dynamic> data = jsonMap['data'] ?? [];
      return data
          .map((postJson) => PostModel.fromJson(
              Map<String, dynamic>.from(postJson as Map<dynamic, dynamic>)))
          .toList();
    } catch (e) {
      Logger.e('API_HOT_POSTS_CACHE', '读取缓存失败: $e');
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(key);
      return null;
    }
  }

  Future<void> _saveHotPostsToCache(
      String key, List<PostModel> posts) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final payload = jsonEncode({
        'timestamp': DateTime.now().toIso8601String(),
        'data': posts.map((post) => post.toJson()).toList(),
      });
      await prefs.setString(key, payload);
    } catch (e) {
      Logger.w('API_HOT_POSTS_CACHE', '保存缓存失败: $e');
    }
  }

  /// 获取动态详情
  /// @param postId 动态ID
  Future<PostModel> getPostDetail(String postId,
      {String requestId = 'get_post_detail'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_POST_DETAIL', '获取动态详情 - postId: $postId');

      final result = await _networkManager.get(
        '/api/hot-page/posts/$postId', // 移除userId参数，让后端从token获取
        requestId: requestId,
      );

      Logger.d('API_POST_DETAIL', '动态详情响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        final postJson = result['data'];
        // 转换后端字段名到前端字段名
        final Map<String, dynamic> convertedJson =
            Map<String, dynamic>.from(postJson);
        convertedJson['user_id'] = postJson['userId'];
        convertedJson['user_avatar'] = postJson['userAvatar'];
        convertedJson['post_type'] = postJson['postType'];
        convertedJson['title'] = postJson['title']; // 添加标题字段转换
        convertedJson['cover_url'] = postJson['coverUrl'];
        convertedJson['likes_count'] = postJson['likesCount'];
        convertedJson['comments_count'] = postJson['commentsCount'];
        convertedJson['shares_count'] = postJson['sharesCount'];
        convertedJson['views_count'] = postJson['viewsCount'];
        convertedJson['is_hot'] = postJson['isHot'];
        convertedJson['skill_tags'] = postJson['tags'] ?? [];
        convertedJson['created_at'] = postJson['createTime'];
        convertedJson['is_liked'] = postJson['isLiked'] ?? false;
        convertedJson['is_followed'] = postJson['isFollowing'] ?? false;
        return PostModel.fromJson(convertedJson);
      } else {
        throw BusinessException(message: result['message'] ?? '获取动态详情失败');
      }
    } catch (e) {
      Logger.e('API_POST_DETAIL', '获取动态详情失败: $e');
      rethrow;
    }
  }

  /// 获取文章详情
  /// @param postId 动态ID
  Future<ArticleModel> getArticleDetail(String postId,
      {String requestId = 'get_article_detail'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_ARTICLE_DETAIL', '获取文章详情 - postId: $postId');

      final result = await _networkManager.get(
        '/api/hot-page/posts/$postId/article', // 移除userId参数，让后端从token获取
        requestId: requestId,
      );

      Logger.d('API_ARTICLE_DETAIL', '文章详情响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        final articleJson = result['data'];
        // 转换后端字段名到前端字段名
        final Map<String, dynamic> convertedJson =
            Map<String, dynamic>.from(articleJson);
        convertedJson['post_id'] = articleJson['postId'];
        convertedJson['content_html'] = articleJson['contentHtml'];
        convertedJson['word_count'] = articleJson['wordCount'];
        convertedJson['created_at'] = articleJson['createdAt'];
        convertedJson['updated_at'] = articleJson['updatedAt'];
        return ArticleModel.fromJson(convertedJson);
      } else {
        throw BusinessException(message: result['message'] ?? '获取文章详情失败');
      }
    } catch (e) {
      Logger.e('API_ARTICLE_DETAIL', '获取文章详情失败: $e');
      rethrow;
    }
  }

  /// 获取视频合集详情
  /// @param postId 动态ID
  Future<VideoCollectionModel> getVideoCollectionDetail(String postId,
      {String requestId = 'get_video_collection_detail'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_VIDEO_COLLECTION', '获取视频合集详情 - postId: $postId');

      final result = await _networkManager.get(
        '/api/hot-page/posts/$postId/video-collection', // 移除userId参数，让后端从token获取
        requestId: requestId,
      );

      Logger.d('API_VIDEO_COLLECTION', '视频合集详情响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        final collectionJson = result['data'];
        // 转换后端字段名到前端字段名
        final Map<String, dynamic> convertedJson =
            Map<String, dynamic>.from(collectionJson);
        convertedJson['post_id'] = collectionJson['postId'];
        convertedJson['cover_url'] = collectionJson['coverUrl'];
        convertedJson['video_count'] = collectionJson['videoCount'];
        convertedJson['created_at'] = collectionJson['createdAt'];
        convertedJson['updated_at'] = collectionJson['updatedAt'];
        return VideoCollectionModel.fromJson(convertedJson);
      } else {
        throw BusinessException(message: result['message'] ?? '获取视频合集详情失败');
      }
    } catch (e) {
      Logger.e('API_VIDEO_COLLECTION', '获取视频合集详情失败: $e');
      rethrow;
    }
  }

  /// 获取服务商品详情
  /// @param postId 帖子ID
  Future<Map<String, dynamic>> getServiceDetail(String postId,
      {String requestId = 'get_service_detail'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_SERVICE_DETAIL', '获取服务商品详情 - postId: $postId');

      final result = await _networkManager.get(
        '/api/hot-page/posts/$postId/service',
        requestId: requestId,
      );

      Logger.d('API_SERVICE_DETAIL', '服务商品详情响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        return result['data'] ?? {};
      } else {
        throw BusinessException(message: result['message'] ?? '获取服务商品详情失败');
      }
    } catch (e) {
      Logger.e('API_SERVICE_DETAIL', '获取服务商品详情失败: $e');
      rethrow;
    }
  }

  /// 收藏/取消收藏服务商品
  /// @param postId 帖子ID
  /// @param isFavorite 是否收藏
  Future<bool> favoriteService(String postId, bool isFavorite,
      {String requestId = 'favorite_service'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_FAVORITE_SERVICE',
          '${isFavorite ? '收藏' : '取消收藏'}服务商品 - postId: $postId');

      final result = await _networkManager.post(
        '/api/hot-page/posts/$postId/favorite',
        data: {'isFavorite': isFavorite},
        requestId: requestId,
      );

      Logger.d('API_FAVORITE_SERVICE', '收藏操作响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        return result['data'] ?? false;
      } else {
        throw BusinessException(message: result['message'] ?? '收藏操作失败');
      }
    } catch (e) {
      Logger.e('API_FAVORITE_SERVICE', '收藏操作失败: $e');
      rethrow;
    }
  }

  /// 咨询服务商品
  /// @param postId 帖子ID
  Future<Map<String, dynamic>> inquireService(String postId,
      {String requestId = 'inquire_service'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_INQUIRE_SERVICE', '咨询服务商品 - postId: $postId');

      final result = await _networkManager.post(
        '/api/hot-page/posts/$postId/inquire',
        requestId: requestId,
      );

      Logger.d('API_INQUIRE_SERVICE', '咨询操作响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        return result['data'] ?? {};
      } else {
        throw BusinessException(message: result['message'] ?? '咨询失败');
      }
    } catch (e) {
      Logger.e('API_INQUIRE_SERVICE', '咨询失败: $e');
      rethrow;
    }
  }

  /// 获取视频合集中的视频列表
  /// @param collectionId 视频合集ID
  Future<List<VideoModel>> getVideoList(String collectionId,
      {String requestId = 'get_video_list'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_VIDEO_LIST', '获取视频列表 - collectionId: $collectionId');

      final result = await _networkManager.get(
        '/api/hot-page/video-collections/$collectionId/videos', // 移除userId参数，让后端从token获取
        requestId: requestId,
      );

      Logger.d('API_VIDEO_LIST', '视频列表响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        final List<dynamic> videosData =
            result['data']['list'] ?? result['data'] ?? [];
        return videosData.map((videoJson) {
          // 转换后端字段名到前端字段名
          final Map<String, dynamic> convertedJson =
              Map<String, dynamic>.from(videoJson);
          convertedJson['collection_id'] = videoJson['collectionId'];
          convertedJson['cover_url'] = videoJson['coverUrl'];
          convertedJson['duration_sec'] = videoJson['durationSec'];
          convertedJson['order_no'] = videoJson['orderNo'];
          convertedJson['created_at'] = videoJson['createdAt'];
          convertedJson['updated_at'] = videoJson['updatedAt'];
          return VideoModel.fromJson(convertedJson);
        }).toList();
      } else {
        throw BusinessException(message: result['message'] ?? '获取视频列表失败');
      }
    } catch (e) {
      Logger.e('API_VIDEO_LIST', '获取视频列表失败: $e');
      rethrow;
    }
  }

  /// 获取动态评论列表
  /// @param postId 动态ID
  /// @param page 页码
  /// @param size 每页大小
  Future<Map<String, dynamic>> getPostComments(String postId,
      {int page = 1, int size = 20, String requestId = 'get_comments'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_GET_COMMENTS',
          '获取动态评论列表 - postId: $postId, page: $page, size: $size');

      final userId = await getUserId() ?? '1';

      final result = await _networkManager.get(
        '/api/comments/post/$postId?userId=$userId&page=$page&size=$size',
        requestId: requestId,
      );

      Logger.d('API_GET_COMMENTS', '获取评论列表响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '获取评论列表失败');
      }

      return result['data'] ?? {};
    } catch (e) {
      Logger.e('API_GET_COMMENTS', '获取评论列表失败: $e');
      rethrow;
    }
  }

  /// 添加评论
  /// @param postId 动态ID
  /// @param content 评论内容
  /// @param parentId 父评论ID（可选，用于回复）
  Future<Map<String, dynamic>> addComment(String postId, String content,
      {String? parentId, String requestId = 'add_comment'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_ADD_COMMENT',
          '添加评论 - postId: $postId, content: $content, parentId: $parentId');

      final userId = await getUserId() ?? '1';

      String url =
          '/api/comments?postId=$postId&userId=$userId&content=${Uri.encodeComponent(content)}';

      if (parentId != null) {
        url += '&parentId=$parentId';
      }

      final result = await _networkManager.post(
        url,
        requestId: requestId,
      );

      Logger.d('API_ADD_COMMENT', '添加评论响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '添加评论失败');
      }

      return result['data'] ?? {};
    } catch (e) {
      Logger.e('API_ADD_COMMENT', '添加评论失败: $e');
      rethrow;
    }
  }

  /// 点赞/取消点赞评论
  /// @param commentId 评论ID
  /// @param isLike true为点赞，false为取消点赞
  Future<void> likeComment(String commentId, bool isLike,
      {String requestId = 'like_comment'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_LIKE_COMMENT',
          '${isLike ? '点赞' : '取消点赞'}评论 - commentId: $commentId');

      final userId = await getUserId() ?? '1';

      final result = await _networkManager.post(
        '/api/comments/$commentId/like?userId=$userId&isLike=$isLike',
        requestId: requestId,
      );

      Logger.d('API_LIKE_COMMENT', '点赞评论响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '点赞评论失败');
      }
    } catch (e) {
      Logger.e('API_LIKE_COMMENT', '点赞评论失败: $e');
      rethrow;
    }
  }

  /// 点赞/取消点赞动态
  /// @param postId 动态ID
  /// @param isLike true为点赞，false为取消点赞
  Future<void> likePost(String postId, bool isLike,
      {String requestId = 'like_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d(
          'API_LIKE_POST', '${isLike ? '点赞' : '取消点赞'}动态 - postId: $postId');

      final result = await _networkManager.post(
        '/api/hot-page/posts/$postId/like?isLike=$isLike',
        requestId: requestId,
      );

      Logger.d('API_LIKE_POST', '点赞操作响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '点赞操作失败');
      }
    } catch (e) {
      Logger.e('API_LIKE_POST', '点赞操作失败: $e');
      rethrow;
    }
  }

  /// 分享动态
  /// @param postId 动态ID
  Future<void> sharePost(String postId,
      {String requestId = 'share_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_SHARE_POST', '分享动态 - postId: $postId');

      final result = await _networkManager.post(
        '/api/hot-page/posts/$postId/share',
        requestId: requestId,
      );

      Logger.d('API_SHARE_POST', '分享操作响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '分享操作失败');
      }
    } catch (e) {
      Logger.e('API_SHARE_POST', '分享操作失败: $e');
      rethrow;
    }
  }

  /// 增加动态浏览量
  /// @param postId 动态ID
  Future<void> viewPost(String postId, {String requestId = 'view_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_VIEW_POST', '增加动态浏览量 - postId: $postId');

      final result = await _networkManager.post(
        '/api/hot-page/posts/$postId/view',
        requestId: requestId,
      );

      Logger.d('API_VIEW_POST', '浏览量增加响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '浏览量增加失败');
      }
    } catch (e) {
      Logger.e('API_VIEW_POST', '浏览量增加失败: $e');
      rethrow;
    }
  }

  /// 发表动态
  /// @param postData 动态数据
  Future<Map<String, dynamic>> publishPost(Map<String, dynamic> postData,
      {String requestId = 'publish_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_PUBLISH_POST', '发表动态 - 数据: $postData');

      // 获取用户ID并添加到请求头中
      final userId = await getUserId();
      if (userId == null) {
        throw NetworkException(message: '用户未登录，请先登录');
      }

      // 设置userId到请求头中
      _networkManager.setHeaders('userId', userId);

      final result = await _networkManager.post(
        '/api/post/publish',
        data: postData,
        requestId: requestId,
      );

      Logger.d('API_PUBLISH_POST', '发表动态响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '发表动态失败');
      }

      return result['data'] ?? {};
    } catch (e) {
      Logger.e('API_PUBLISH_POST', '发表动态失败: $e');
      rethrow;
    }
  }

  /// 更新动态
  /// @param postId 动态ID
  /// @param updateData 更新数据
  Future<Map<String, dynamic>> updatePost(
      String postId, Map<String, dynamic> updateData,
      {String requestId = 'update_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_UPDATE_POST', '更新动态 - ID: $postId, 数据: $updateData');

      // 获取用户ID并添加到请求头中
      final userId = await getUserId();
      if (userId == null) {
        throw NetworkException(message: '用户未登录，请先登录');
      }

      // 设置userId到请求头中
      _networkManager.setHeaders('userId', userId);

      final result = await _networkManager.put(
        '/api/post/update/$postId',
        data: updateData,
        requestId: requestId,
      );

      Logger.d('API_UPDATE_POST', '更新动态响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '更新动态失败');
      }

      return result['data'] ?? {};
    } catch (e) {
      Logger.e('API_UPDATE_POST', '更新动态失败: $e');
      rethrow;
    }
  }

  /// 删除动态（软删除）
  /// @param postId 动态ID
  Future<Map<String, dynamic>> deletePost(String postId,
      {String requestId = 'delete_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_DELETE_POST', '删除动态 - ID: $postId');

      // 获取用户ID并添加到请求头中
      final userId = await getUserId();
      if (userId == null) {
        throw NetworkException(message: '用户未登录，请先登录');
      }

      // 设置userId到请求头中
      _networkManager.setHeaders('userId', userId);

      final result = await _networkManager.delete(
        '/api/post/delete/$postId',
        requestId: requestId,
      );

      Logger.d('API_DELETE_POST', '删除动态响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '删除动态失败');
      }

      // 处理返回的数据，可能是字符串或Map
      final data = result['data'];
      if (data is String) {
        return {'message': data};
      } else if (data is Map<String, dynamic>) {
        return data;
      } else {
        return {'message': '删除成功'};
      }
    } catch (e) {
      Logger.e('API_DELETE_POST', '删除动态失败: $e');
      rethrow;
    }
  }

  /// 举报动态
  /// @param postId 动态ID
  /// @param reason 举报原因
  Future<Map<String, dynamic>> reportPost(String postId, String reason,
      {String requestId = 'report_post'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_REPORT_POST', '举报动态 - ID: $postId, 原因: $reason');

      // 获取用户ID并添加到请求头中
      final userId = await getUserId();
      if (userId == null) {
        throw NetworkException(message: '用户未登录，请先登录');
      }

      // 设置userId到请求头中
      _networkManager.setHeaders('userId', userId);

      final result = await _networkManager.post(
        '/api/post/report',
        data: {
          'postId': postId,
          'reason': reason,
        },
        requestId: requestId,
      );

      Logger.d('API_REPORT_POST', '举报动态响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '举报失败');
      }

      return result['data'] ?? {};
    } catch (e) {
      Logger.e('API_REPORT_POST', '举报动态失败: $e');
      rethrow;
    }
  }

  /// 获取内容分类列表
  Future<List<dynamic>> getContentCategories(
      {String requestId = 'get_categories'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_GET_CATEGORIES', '获取内容分类列表');

      final result = await _networkManager.get(
        '/api/post/categories',
        requestId: requestId,
      );

      Logger.d('API_GET_CATEGORIES', '获取分类响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '获取分类失败');
      }

      return result['data'] ?? [];
    } catch (e) {
      Logger.e('API_GET_CATEGORIES', '获取分类失败: $e');
      rethrow;
    }
  }

  /// 检查发布权限
  /// @param postType 动态类型
  Future<Map<String, dynamic>> checkPublishPermission(String postType,
      {String requestId = 'check_permission'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_CHECK_PERMISSION', '检查发布权限 - postType: $postType');

      // 获取用户ID并添加到请求头中
      final userId = await getUserId();
      if (userId == null) {
        throw NetworkException(message: '用户未登录，请先登录');
      }

      // 设置userId到请求头中
      _networkManager.setHeaders('userId', userId);

      final result = await _networkManager.get(
        '/api/post/check-permission?postType=$postType',
        requestId: requestId,
      );

      Logger.d('API_CHECK_PERMISSION', '权限检查响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '权限检查失败');
      }

      return result['data'] ?? {};
    } catch (e) {
      Logger.e('API_CHECK_PERMISSION', '权限检查失败: $e');
      rethrow;
    }
  }

  // ==================== 用户动态管理相关接口 ====================

  /// 获取用户动态列表
  /// @param userId 用户ID
  /// @param page 页码
  /// @param size 每页大小
  Future<List<PostModel>> getUserPosts({
    required String userId,
    int page = 1,
    int size = 10,
    String requestId = 'get_user_posts',
  }) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_USER_POSTS',
          '获取用户动态列表 - userId: $userId, page: $page, size: $size');

      final result = await _networkManager.get(
        '/api/user-posts',
        params: {
          'userId': userId,
          'page': page,
          'size': size,
        },
        requestId: requestId,
      );

      Logger.d('API_USER_POSTS', '用户动态列表响应: $result');

      if (result['code'] == 200 || result['code'] == 0) {
        final List<dynamic> postsData =
            result['data']['list'] ?? result['data'] ?? [];
        return postsData.map((postJson) {
          // 🔍 添加详细的日志输出，调试图片显示问题
          Logger.d('API_USER_POSTS_DATA', '========== 个人动态原始数据 ==========');
          Logger.d('API_USER_POSTS_DATA', 'ID: ${postJson['id']}');
          Logger.d('API_USER_POSTS_DATA', '用户: ${postJson['userNickname']}');
          Logger.d('API_USER_POSTS_DATA', '类型: ${postJson['postType']}');
          Logger.d('API_USER_POSTS_DATA', '标题: ${postJson['title']}');
          Logger.d('API_USER_POSTS_DATA', '内容: ${postJson['content']}');
          Logger.d(
              'API_USER_POSTS_DATA', '封面URL (原始): ${postJson['coverUrl']}');
          Logger.d('API_USER_POSTS_DATA', '图片列表 (原始): ${postJson['images']}');
          Logger.d(
              'API_USER_POSTS_DATA', '图片类型: ${postJson['images'].runtimeType}');
          Logger.d('API_USER_POSTS_DATA', '=============================');

          // 转换后端字段名到前端字段名
          final Map<String, dynamic> convertedJson =
              Map<String, dynamic>.from(postJson);
          convertedJson['user_id'] = postJson['userId'];
          convertedJson['username'] = postJson['userNickname'];
          convertedJson['user_avatar'] = postJson['userAvatar'];
          convertedJson['post_type'] = postJson['postType'];
          convertedJson['title'] = postJson['title']; // 添加标题字段转换
          convertedJson['cover_url'] = postJson['coverUrl'];
          convertedJson['likes_count'] = postJson['likesCount'];
          convertedJson['comments_count'] = postJson['commentsCount'];
          convertedJson['shares_count'] = postJson['sharesCount'];
          convertedJson['views_count'] = postJson['viewsCount'];
          convertedJson['is_hot'] = postJson['isHot'];
          convertedJson['skill_tags'] = postJson['tags'] ?? [];
          convertedJson['created_at'] = postJson['createTime'];
          convertedJson['is_liked'] = postJson['isLiked'] ?? false;
          convertedJson['is_followed'] = postJson['isFollowing'] ?? false;
          convertedJson['visibility'] = postJson['visibility'] ?? 'public';

          final post = PostModel.fromJson(convertedJson);
          Logger.d('API_USER_POSTS_DATA',
              '转换后PostModel - images数量: ${post.images.length}, images: ${post.images}');

          return post;
        }).toList();
      } else {
        throw BusinessException(message: result['message'] ?? '获取用户动态列表失败');
      }
    } catch (e) {
      Logger.e('API_USER_POSTS', '获取用户动态列表失败: $e');
      rethrow;
    }
  }

  /// 设置动态隐私
  /// @param postId 动态ID
  /// @param visibility 隐私设置：public-公开，private-私密，friends-仅好友可见
  Future<Map<String, dynamic>> setPostVisibility(
      String postId, String visibility,
      {String requestId = 'set_post_visibility'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_SET_VISIBILITY',
          '设置动态隐私 - postId: $postId, visibility: $visibility');

      final result = await _networkManager.post(
        '/api/post/set-visibility/$postId?visibility=$visibility',
        requestId: requestId,
      );

      Logger.d('API_SET_VISIBILITY', '设置隐私响应: $result');

      if (result['code'] != 200 && result['code'] != 0) {
        throw BusinessException(message: result['message'] ?? '设置隐私失败');
      }

      // 处理返回的数据，可能是字符串或Map
      final data = result['data'];
      if (data is String) {
        return {'message': data};
      } else if (data is Map<String, dynamic>) {
        return data;
      } else {
        return {'message': '设置成功'};
      }
    } catch (e) {
      Logger.e('API_SET_VISIBILITY', '设置动态隐私失败: $e');
      rethrow;
    }
  }

  /// 上传图片（通用）
  /// @param imageFile 图片文件
  /// @param requestId 请求ID
  /// 
  /// 使用后端的 /api/user/upload/post-image 接口
  Future<Map<String, dynamic>> uploadImage(File imageFile,
      {String requestId = 'upload_image'}) async {
    final isConnected = await checkNetworkConnection();
    if (!isConnected) {
      throw NetworkException(message: '网络连接不可用，请检查网络设置');
    }

    try {
      Logger.d('API_UPLOAD_IMAGE', '开始上传图片: ${imageFile.path}');
      
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(imageFile.path,
            filename: imageFile.path.split('/').last),
      });

      final result = await _networkManager.post<Map<String, dynamic>>(
        '/api/user/upload/post-image',  // 使用正确的后端接口路径
        data: formData,
        contentType: 'multipart/form-data',
        requestId: requestId,
      );

      Logger.d('API_UPLOAD_IMAGE', '上传响应: $result');

      if (result['code'] == 200) {
        // 后端返回的是直接的URL字符串，需要包装成map
        final url = result['data'];
        if (url is String) {
          return {'url': url};
        }
        return result['data'] ?? {};
      } else {
        throw BusinessException(message: result['message'] ?? '图片上传失败');
      }
    } catch (e) {
      Logger.e('API_UPLOAD_IMAGE', '图片上传失败: $e');
      rethrow;
    }
  }

  // ==================== 个人资料管理相关API ====================

  /// 获取用户个人资料
  Future<UserProfileModel> getUserProfile(String userId,
      {String requestId = 'get_user_profile'}) async {
    try {
      Logger.d('API_USER_PROFILE', '获取用户个人资料，用户ID: $userId');

      final result = await _networkManager.get(
        '/api/user/profile/$userId',
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        final profile = UserProfileModel.fromJson(result['data']);
        Logger.d('API_USER_PROFILE', '获取用户个人资料成功');
        return profile;
      } else {
        Logger.e('API_USER_PROFILE', '获取用户个人资料失败: ${result['message']}');
        throw NetworkException(message: '获取个人资料失败');
      }
    } catch (e) {
      Logger.e('API_USER_PROFILE', '获取用户个人资料异常: $e');
      rethrow;
    }
  }

  /// 更新用户个人资料
  Future<UserProfileModel> updateUserProfile(
      String userId, UpdateUserProfileDTO updateData,
      {String requestId = 'update_user_profile'}) async {
    try {
      Logger.d('API_USER_PROFILE', '更新用户个人资料，用户ID: $userId');

      final result = await _networkManager.put(
        '/api/user/profile/$userId',
        data: updateData.toJson(),
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        final profile = UserProfileModel.fromJson(result['data']);
        Logger.d('API_USER_PROFILE', '更新用户个人资料成功');
        return profile;
      } else {
        Logger.e('API_USER_PROFILE', '更新用户个人资料失败: ${result['message']}');
        throw NetworkException(message: '更新个人资料失败');
      }
    } catch (e) {
      Logger.e('API_USER_PROFILE', '更新用户个人资料异常: $e');
      rethrow;
    }
  }

  /// 获取所有可用的技能标签
  Future<List<UserTagModel>> getAvailableTags(
      {String requestId = 'get_available_tags'}) async {
    try {
      Logger.d('API_USER_TAGS', '获取所有可用的技能标签');

      final result = await _networkManager.get(
        '/api/user/profile/tags/available',
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        final List<dynamic> tagsData = result['data'];
        final tags =
            tagsData.map((tagJson) => UserTagModel.fromJson(tagJson)).toList();
        Logger.d('API_USER_TAGS', '获取技能标签成功，数量: ${tags.length}');
        return tags;
      } else {
        Logger.e('API_USER_TAGS', '获取技能标签失败: ${result['message']}');
        throw NetworkException(message: '获取技能标签失败');
      }
    } catch (e) {
      Logger.e('API_USER_TAGS', '获取技能标签异常: $e');
      rethrow;
    }
  }

  /// 更新用户技能标签
  Future<bool> updateUserSkillTags(String userId, List<String> skillTags,
      {String requestId = 'update_user_skill_tags'}) async {
    try {
      Logger.d(
          'API_USER_TAGS', '更新用户技能标签，用户ID: $userId，标签数量: ${skillTags.length}');

      final result = await _networkManager.put(
        '/api/user/profile/$userId/tags',
        data: skillTags,
        requestId: requestId,
      );

      if (result['code'] == 200) {
        Logger.d('API_USER_TAGS', '更新用户技能标签成功');
        return true;
      } else {
        Logger.e('API_USER_TAGS', '更新用户技能标签失败: ${result['message']}');
        throw NetworkException(message: '更新技能标签失败');
      }
    } catch (e) {
      Logger.e('API_USER_TAGS', '更新用户技能标签异常: $e');
      rethrow;
    }
  }

  // ==================== 订单相关接口 ====================

  /// 创建订单
  Future<Map<String, dynamic>> createOrder(int serviceProductId,
      {int quantity = 1, String requestId = 'create_order'}) async {
    try {
      Logger.d('API_ORDER', '创建订单，商品ID: $serviceProductId，数量: $quantity');

      final result = await _networkManager.post(
        '/api/orders/create',
        data: {
          'serviceProductId': serviceProductId,
          'quantity': quantity,
        },
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        Logger.d('API_ORDER', '创建订单成功');
        return result['data'];
      } else {
        Logger.e('API_ORDER', '创建订单失败: ${result['message']}');
        throw NetworkException(message: result['message'] ?? '创建订单失败');
      }
    } catch (e) {
      Logger.e('API_ORDER', '创建订单异常: $e');
      rethrow;
    }
  }

  /// 支付订单
  Future<Map<String, dynamic>> payOrder(int orderId,
      {String paymentMethod = 'balance',
      String requestId = 'pay_order'}) async {
    try {
      Logger.d('API_ORDER', '支付订单，订单ID: $orderId，支付方式: $paymentMethod');

      final result = await _networkManager.post(
        '/api/orders/$orderId/pay',
        data: {
          'paymentMethod': paymentMethod,
        },
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        Logger.d('API_ORDER', '支付订单成功');
        return result['data'];
      } else {
        Logger.e('API_ORDER', '支付订单失败: ${result['message']}');
        throw NetworkException(message: result['message'] ?? '支付订单失败');
      }
    } catch (e) {
      Logger.e('API_ORDER', '支付订单异常: $e');
      rethrow;
    }
  }

  /// 获取订单详情
  Future<Map<String, dynamic>> getOrderDetail(int orderId,
      {String requestId = 'get_order_detail'}) async {
    try {
      Logger.d('API_ORDER', '获取订单详情，订单ID: $orderId');

      final result = await _networkManager.get(
        '/api/orders/$orderId',
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        Logger.d('API_ORDER', '获取订单详情成功');
        return result['data'];
      } else {
        Logger.e('API_ORDER', '获取订单详情失败: ${result['message']}');
        throw NetworkException(message: result['message'] ?? '获取订单详情失败');
      }
    } catch (e) {
      Logger.e('API_ORDER', '获取订单详情异常: $e');
      rethrow;
    }
  }

  /// 获取我的订单列表
  Future<List<Map<String, dynamic>>> getMyOrders(
      {String? status, String requestId = 'get_my_orders'}) async {
    try {
      Logger.d('API_ORDER', '获取我的订单列表，状态: $status');

      final params = <String, dynamic>{};
      if (status != null && status.isNotEmpty) {
        params['status'] = status;
      }

      final result = await _networkManager.get(
        '/api/orders/my-orders',
        params: params,
        requestId: requestId,
      );

      if (result['code'] == 200 && result['data'] != null) {
        final List<dynamic> ordersData = result['data'];
        Logger.d('API_ORDER', '获取订单列表成功，数量: ${ordersData.length}');
        return ordersData.cast<Map<String, dynamic>>();
      } else {
        Logger.e('API_ORDER', '获取订单列表失败: ${result['message']}');
        throw NetworkException(message: result['message'] ?? '获取订单列表失败');
      }
    } catch (e) {
      Logger.e('API_ORDER', '获取订单列表异常: $e');
      rethrow;
    }
  }

  /// 取消订单
  Future<bool> cancelOrder(int orderId,
      {String requestId = 'cancel_order'}) async {
    try {
      Logger.d('API_ORDER', '取消订单，订单ID: $orderId');

      final result = await _networkManager.post(
        '/api/orders/$orderId/cancel',
        requestId: requestId,
      );

      if (result['code'] == 200) {
        Logger.d('API_ORDER', '取消订单成功');
        return true;
      } else {
        Logger.e('API_ORDER', '取消订单失败: ${result['message']}');
        throw NetworkException(message: result['message'] ?? '取消订单失败');
      }
    } catch (e) {
      Logger.e('API_ORDER', '取消订单异常: $e');
      rethrow;
    }
  }
}
